/**
 * 物料相关
 */
var totalPrice = 0;
$(document).ready(function () {


	if(navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion .split(";")[1].replace(/[ ]/g,"")=="MSIE8.0"){
		var $moudle = $('#data-moudle');
		var module = $moudle.val();
		var $id = $('#data-id');
		var id = $id.val();
	}else{

	var $body = $('body');
	var module = $body.data('moudle');
	var id = $body.data('id');

	}


	//预算总价计算
	var $totalPrice = $('#totalPrice');
	var $requestItemTable = $('#datatable-requestItemTable');
	var pagePriceSum = 0;//当前页码原始值
	totalPrice = (+$totalPrice.html())||0;
	$requestItemTable.on('input propertychange','.js-change', function () {
		var sum = countTotalPrice();
		totalPrice = totalPrice + sum - pagePriceSum;
		pagePriceSum = sum;
		$totalPrice.html((totalPrice + sum - pagePriceSum).toFixed(2));
		var param = +this.value;
        if (!param || param <= 0) {
            RFQ.error('请输入大于0的数字');
        }
	});

	//预算价选择项点击
	$requestItemTable.on('click','.dropdown-menu a', function () {
		var index = $(this).parent().index();
		var url = ctx+'/rfqRequest/updateSalePriceByRecent';
		if(index == 1){
			url = ctx+'/rfqRequest/updateSalePriceByHistory';
		}
		//设置默认预算价
		$requestItemTable.find('input[data-name$="salePrice"]').each(function () {
			if(!this.value.length){
				this.value = 0;
			}
		});

		var rfqDtable = $requestItemTable.data('_rfqDTable');
		//保存当页数据
		if(rfqDtable.options.beforePagination.call(rfqDtable)){
			RFQ.post(url,{}, function (data) {
				totalPrice = +data.obj;
				$totalPrice.html(totalPrice.toFixed(2));
			},false);
			rfqDtable.load();
		}
	});

	//计算总价
	function countTotalPrice(){
		var sum = 0;
		$requestItemTable.find("input[data-name='requestAmount']").each(function(){
			var $this = $(this);
			var $tr = $this.closest('tr');
			var requestAmount = +this.value;
			var salePrice = +$tr.find('input[data-name="salePrice"]').val();
			(!requestAmount || requestAmount<0) && (requestAmount = 0);
			(!salePrice || salePrice<0) && (salePrice = 0);
			sum += (requestAmount*salePrice);
		});
		return sum;
	}


	//物料分页加载
	//var $zuiDataTable = $('#requestItemTable');
	(function () {
		var inputTpl;
		var _mappingNames;
		var mappingdis;
		var clsMapping = {requestAmount:'js-change',salePrice:'js-change',requestDeliveryDate:'form-date'};
		if($("#dataSource").val() =='ygck'||$("#dataSource").val() =='ygzb'){
			inputTpl = '<input type="text" class="form-control input-sm {cls}" data-name="{name}" value="{value}" data-ext="{ext}" maxlength="{limit}" {dis}>';//输入框
			_mappingNames = ['materialNo','materialName','character','producer','requestAmount','unit','salePrice','requestDeliveryDate','memo'];
			mappingdis={materialNo:'disabled',materialName:'disabled',character:'disabled',producer:'disabled',requestAmount:'disabled',unit:'disabled',salePrice:'disabled',requestDeliveryDate:'disabled',memo:'disabled'};
		}else if($("#dataSource").val() =='JFE'){
			inputTpl = '<input type="text" class="form-control input-sm {cls}" data-name="{name}" value="{value}" data-ext="{ext}" maxlength="{limit}" {dis}>';//输入框
			_mappingNames = ['materialNo','materialName','character','producer','requestAmount','unit','salePrice','requestDeliveryDate','purchaseNo','purchasePerson','drawingNo','memo'];
			mappingdis={materialNo:'disabled',materialName:'disabled',character:'disabled',producer:'disabled',requestAmount:'disabled',unit:'disabled',salePrice:'disabled',requestDeliveryDate:'disabled',purchaseNo:'disabled',purchasePerson:'disabled',drawingNo:'disabled',memo:'disabled'};
		}else if($("#dataSource").val() =='NBBX'){
			inputTpl = '<input type="text" class="form-control input-sm {cls}" data-name="{name}" value="{value}" data-ext="{ext}" maxlength="{limit}" {dis}>';//输入框
			_mappingNames = ['materialNo','materialName','character','producer','requestAmount','unit','salePrice','requestDeliveryDate','drawingNo','memo'];
			mappingdis={materialNo:'disabled',materialName:'disabled',character:'disabled',producer:'disabled',requestAmount:'disabled',unit:'disabled',salePrice:'disabled',requestDeliveryDate:'',drawingNo:'disabled',memo:''};
		}else{
			inputTpl = '<input type="text" class="form-control input-sm {cls}" data-name="{name}" value="{value}" data-ext="{ext}" maxlength="{limit}" {dis}>';//输入框
			_mappingNames = ['materialNo','materialName','character','producer','requestAmount','unit','salePrice','requestDeliveryDate','memo'];
			mappingdis={materialNo:'',materialName:'',character:'',producer:'',requestAmount:'',unit:'',salePrice:'',requestDeliveryDate:'',memo:''};
		}
		var _mappingLimits ={materialNo:200,materialName:400,character:200,producer:50,requestAmount:25,unit:20,salePrice:25,requestDeliveryDate:20,memo:2000};
		//获取自定义字段
		var extColsMapping = {};
		$('#requestItemTable').find('th.ext-col').each(function (i) {
			var $this = $(this);
			var extCode = $this.data('extcode');
			var valName = 'itemValue_'+(i+1);
			extColsMapping[valName] = extCode;
			_mappingNames.push(valName);
		});
		var boo;
		if($("#dataSource").val() =='ygck' || $("#dataSource").val() =='ygzb'||$("#dataSource").val() =='JFE'||$("#dataSource").val() =='NBBX'){
			boo=false;//不显示删除操作按钮
		}else{
			boo=true;
		}
		var options = {
			renderDel:boo,
			datatype: 'json',
			url:ctx+'/rfqRequest/rfqRequestItemList',
            sord:'ASC',
            sidx:'SEQ',
			mappingNames: _mappingNames,
			cellFormat: function (name,val,row,index) {
				if(name=='salePrice'){
					val =  val == "" ? '0.000' : val;
				}
				var tmp = inputTpl.format({name:name,value:val||'',cls:clsMapping[name]||'',ext:extColsMapping[name]||'',limit:_mappingLimits[name]||100,dis:mappingdis[name]||''});
				//if(row && name == 'materialNo'){
				//	tmp += '<input type="hidden" data-name="id" value="'+(row.id||'')+'">';
				//}
				return tmp;
			},
			afterLoadData: function () {
				var that = this;
				this.visibleObj.find('.form-date').datetimepicker({
					weekStart: 1,
					todayBtn:  1,
					autoclose: 1,
					todayHighlight: 1,
					startView: 2,
					minView: 2,
					forceParse: 0,
					format: "yyyy-mm-dd"
				});
				//给要求交货期添加事件
				$('.requestDeliveryDate.datetimepicker .datetimepicker-days').on('click','tbody td,tfoot th',function () {
                setTimeout(function () {
                    $requestItemTable.find('input[data-name="requestDeliveryDate"]').val($('#requestDeliveryDate2.form-control').eq(1).val());
                }, 100);
                    var extras = that.fetchChanges('requestItemList');
                    // RFQ.post(ctx + '/rfqRequest/check4Item', extras, function (msg) {
                    //     if (msg.rspcod == '200') {
                    //         return;
                    //     } else if (msg.rspcod == '201') {
                    //         RFQ.warn(msg.rspmsg)
                    //     }
                    // }, false);
                });
                

				pagePriceSum = countTotalPrice();
			},
			beforePagination: function () {
				//分页前保存数据
				var that = this;
				var extras = that.fetchChanges('requestItemList');
				RFQ.d(extras);
				var canPass = false;
				RFQ.post(ctx+'/rfqRequest/save2temp?rfqRequestNo='+$("#requestId").val(),extras, function (msg) {
					//数据置空
					if(msg.rspcod =='200'){
					canPass = true;
					that.deleteIds = [];
					var messageList1 = msg.obj.messageList1;
					//console.log('messageList'+messageList1);
					if(messageList1!="" && messageList1!=null){
						RFQ.warn(messageList1)
					}
					}else if(msg.rspcod == '201'){
                        RFQ.warn(msg.rspmsg)
					}
				},false);
				return canPass;
			}
		};

		var rfqDTable = RFQ.dataTable('#requestItemTable').init(options);

		$requestItemTable.data('_rfqDTable',rfqDTable);
		if('edit'!=module){
			rfqDTable.load({},true);
		}else{
			rfqDTable.load();
		}

		//新增一行数据
		$('#addRow').on('click', function () {
			rfqDTable.addRow();
		});

		//清空物料
		$('#clearData').on('click', function () {
			RFQ.confirm('是否确认清空物料？', function () {
				RFQ.post(ctx+'/rfqRequest/deleteRequestItemTmpData',{}, function (msg) {
					rfqDTable.clear();
					rfqDTable.deleteIds = [];
					totalPrice = 0;
					pagePriceSum = 0;
					$totalPrice.html(totalPrice.toFixed(2));
					rfqDTable.load();//清空数据后刷新jqgrid
				},false);
			});
		});

		//删除一行
		$requestItemTable.on('click','.js-del', function () {
			var $this = $(this);
			var $tr = $this.closest('tr');
			var index = $tr.data('index');
			var sumTmp = pagePriceSum;
			//重新计算当前页的总价
			// rfqDTable.delRow(index);
			totalPrice -= (sumTmp - pagePriceSum);
			$totalPrice.html(totalPrice.toFixed(2));
			var id = $this.next('input').val();
			if(id){
				RFQ.post(ctx+'/rfqRequest/deleteRequestItemTmpData2?id='+id,null,function (msg) {
                    rfqDTable.deleteIds.push(id);
				    rfqDTable.load();
				},false);
			}else{
				rfqDTable.delRow(index);
			}

		});
	})();
});
//excel模板导出
function exportExcelModel(){
	location.href=ctx+'/rfqRequestItem/exportTemplate';
}

//excel导出
function exportExcel(){
	$.ajax({
		type: "POST",
		url: ctx+"/rfqRequestItem/exportRecord",
		data: {
			requestId: $('#requestId').val()
		},
		success: function(data) {
			if ("success"==data.status) {
				/*//预算总价
				var budgetPrice = data.budgetPrice;
				console.log("budgetPrice:"+budgetPrice);*/
				location.href=data.message;
			} else {
				RFQ.error('sorry,出错了！');
			};
		}
	});
}

function saveExcel(){
	//校验是否有输入文件
	var $file = $('#file');
	if(!$file[0].value){
		RFQ.error('您还未选择文件');
		return;
	}
	$('#excelUpload').ajaxSubmit({
		success: function (data) {
            var data;
            try
            {
                data = eval('('+data+')');
            }
            catch (e)
            {
                data = jQuery.parseJSON(jQuery(data).text());          //兼容ie8不返回PRE的解析方式,如果发生异常说明带PRE,部分IE9是带PRE的
            }
			if (data.status == 'success') {
				var messageList = data.messageList;
				//console.log('messageList'+messageList);
				//预算总价
				var budgetPrice = +data.budgetPrice;
				if(messageList!="" && messageList!=null){
					RFQ.warn(data.message+"["+messageList+"]");
				}else{
					RFQ.info(data.message);
				}
				$('#cancelPrice33').modal('hide');
				//临时表加载数据
				$('#datatable-requestItemTable').data('_rfqDTable').load();
				//预算价
				totalPrice = budgetPrice;
				$('#totalPrice').html(totalPrice.toFixed(2));
			} else {
				RFQ.error(data.message);
			}
		}
	});
}
